<?php

namespace app\admin\controller;

use brand\Brand;
use brand\build\Columns;
use brand\logic\BrandHelper;
use brand\page\Form;
use brand\page\Table;
use think\addons\AddonException;
use think\AddonService;
use think\facade\Cache;
use think\facade\View;
use think\File;

class BrandAddons extends Base
{


    public function init_curd()
    {
        parent::init_curd();
        $this->pk = 'name';
        $columns['name'] = Brand::Builder('名称')->build();
        $columns['title'] = Brand::Builder('标题')->build();
        $columns['intro'] = Brand::Builder('简介')->build();
        $columns['state'] = Brand::Builder('状态')->table_action_type('switcher')->build();
        Table::$right_buttons = [];
        Table::$header_buttons = ['add'];



        Table::$custom_button[] = Brand::Builder()
            ->build_button('卸载','el-icon-delete-solid','confirm')
            ->button_confirm('确定要卸载吗？')
            ->button_url(url('delete_addon')->build())
            ->button_data(['name'])
            ->build();
        Table::$custom_button[] = Brand::Builder()
            ->build_button('配置','el-icon-s-tools')
            ->button_url(url('set_addon')->build())
            ->button_data(['name'])
            ->build();
        Table::$custom_button[] = Brand::Builder()
            ->build_button('数据表管理','el-icon-s-tools')
            ->button_url(url('tables')->build())
            ->button_data(['name'])
            ->form_visible([['prop' => 'table_prefix', 'value' => true]])
            ->build();
        Columns::setConfig($columns);
    }

    /**
     * 本地安装
     */
    public function add()
    {
        if ($this->request->isAjax()){

            $file = $this->request->param('file');
            try {
                //安装本地插件
                AddonService::local($file);
            } catch (AddonException $e) {
                $this->result($e->getData(), $e->getCode(), __($e->getMessage()));
            } catch (\Exception $e) {
                $this->error(__($e->getMessage()));
            }
            $this->success('操作成功');
            exit;
        }

        $raw = [];
        $columns['file'] = Brand::Builder('上传文件')
            ->method_upload()
            ->form_props(['fileType'=>'file'])
            ->form_marker('压缩包为.zip文件，压缩包内直接为插件文件，不要有文件夹包裹。')
            ->build();
        $columns_arr = Form::buildForm($columns,$raw);

        Form::buildColumns($columns_arr);

        return Form::buildView();
    }
    

    public function _tabledata()
    {
        $list = get_addon_list();
        $list = array_values($list);
        foreach ($list as $key => $item) {
            if (isset($item['table_prefix']) && $item['table_prefix']){
                $list[$key]['table_prefix'] = true;
            }else{
                $list[$key]['table_prefix'] = false;
            }
        }
        return _success('',['count'=>count($list),'list'=>$list]);
    }

    public function set_addon()
    {

        $name = $this->request->get('name');
        $configs = get_addon_fullconfig($name);

        if ($this->request->isAjax()){

            $params = $this->request->param();
            foreach ($configs as $key => $config) {

                $value = $params[$config['name']];

                $configs[$key]['value'] = $value;
            }
            //更新配置文件
            set_addon_fullconfig($name, $configs);
            $this->success();
        }
        $columns = [];
        $values = [];
        foreach ($configs as $config) {
            $options = $config['options'] ?? [];
            $value = $config['value'];

            if (isset($config['type']) && $config['type'] == 'arrays'){

                if (isset($config['options']) && $config['options']){
                    $options = [];
                    foreach ($config['options'] as $key => $label) {
                        $options[$key] = Brand::Builder($label)->build();
                    }
                }
                $options = [$options];
            }elseif(isset($config['type']) && in_array($config['type'],['checkbox'])){
                $options = BrandHelper::formatOptions($options);
            }

            $columns[$config['name']] = Brand::Builder($config['title'],$config['type'] ?? 'input')->form_options($options)->build();

            $values[$config['name']] = $value;
        }

        $columns_arr = Form::buildForm($columns,$values);
        Form::buildColumns($columns_arr);
        return Form::buildView();
    }

    /**
     * 设置
     * @param false $add
     */
    public function edit($add = false)
    {
        $field = $this->request->param('field');
        $name = $this->request->param('name');
        $value = $this->request->param('value');
        if ($field == 'state'){
            $action = $value == 1 ? 'enable' : 'disable';
            $this->state($name,$action,$value);
        }
    }

    /**
     * 禁用启用
     */
    public function state($name,$action,$force)
    {

        if (!$name) {
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error(__('Addon name incorrect'));
        }
        try {
            $action = $action == 'enable' ? $action : 'disable';
            //调用启用、禁用的方法
            AddonService::$action($name, $force);
            Cache::delete('__menu__');
        } catch (AddonException $e) {
            $this->result($e->getData(), $e->getCode(), __($e->getMessage()));
        } catch (\Exception $e) {
            $this->error(__($e->getMessage()));
        }
        $this->success('操作成功');
    }

    public function delete_addon()
    {
        $name = $this->request->param('name');
        try {
            //调用启用、禁用的方法
            AddonService::uninstall($name);
        } catch (AddonException $e) {
            $this->result($e->getData(), $e->getCode(), __($e->getMessage()));
        } catch (\Exception $e) {
            $this->error(__($e->getMessage()));
        }
        $this->success('操作成功');
    }

    /**
     * 插件数据库
     */
    public function tables()
    {
        $addon = $this->request->param('name');
        $this->redirect(url(BrandHelper::getAdminName().'/curd/table',['addon'=>$addon])->build());
    }


}